<?php
declare (strict_types = 1);

namespace app\home\controller;

use app\BaseController;
use app\common\model\Config as ConfigModel;
use app\common\model\Post\Cate as CateModel;
use app\common\model\Post\Post as PostModel;
use app\common\model\User\User as UserModel;
use app\common\model\User\Record as RecordModel;
use app\common\model\Collect as CollectModel;
use app\common\model\Post\Comment as CommentModel;
use app\common\validate\Post\Post as PostValiDate;
use think\exception\ValidateException;
use app\common\validate\User\Record as RecordValiDate;

class Post extends BaseController
{
    // 设置控制器中间件
    protected $middleware = [
        \app\home\middleware\LoginAuth::class => ['except' => 'info']
    ];

    protected function initialize()
    {
        $this->PostModel = new PostModel();
        
        $this->RecordModel = new RecordModel();
        
    }

    // 帖子详情
    public function info()
    {
        $LoginUser = !empty(cookie('LoginUser')) ? json_decode(cookie('LoginUser'),true) : [];

        $userid = !empty($LoginUser['id']) ? $LoginUser['id'] : 0;

        $postid = $this->request->param('postid');

        $post = $this->PostModel->withJoin(['user','type'])->where(['post.id' => $postid])->find();

        if(!$post)
        {
            $this->error('帖子不存在，请重新选择');
        }

        $VisitArr = explode(',',(String)$post['visit']);

        // 过滤数组空元素
        $VisitArr = array_filter($VisitArr);


        if($userid)
        {
            // in_array 查找某个值是否在数组里
            if(!in_array($userid,$VisitArr))
            {
                $VisitArr[] = $userid;

                $VisitStr = implode(',',$VisitArr);

                $this->PostModel->where('id',$postid)->update(['visit' => $VisitStr]);
            }
        }

        // $VisitStr = $this->PostModel->where('id',$postid)->value('visit');

        // $VisitArr = explode(',',$VisitStr);

        // $VisitCount = count($VisitArr);

        $post = $this->PostModel->withJoin(['user','type'])->where(['post.id' => $postid])->find();

         // 查询当前用户是否收藏该帖子
        $collect = CollectModel::where(['userid' => $userid,'postid' => $postid])->find();

         // 查询评论数据
        $CommentList = CommentModel::withJoin(['user'])->where(['postid' => $postid])->order('id', 'asc')->order('level', 'asc')->select();

        $CommentList = CommentTree($CommentList,0,$LoginUser);

        return view('',[
            'post' => $post,
            'userid' => $userid,
            'LoginUser' => $LoginUser,
            'collect' => $collect,
            'CommentList' => $CommentList
            // 'VisitCount' => $VisitCount
        ]);
    }

    // 帖子修改
    public function edit()
    {
        // 接收帖子id
        $postid = $this->request->param('postid');

        $LoginUser = !empty(cookie('LoginUser')) ? json_decode(cookie('LoginUser'),true) : [];

        $userid = !empty($LoginUser['id']) ? $LoginUser['id'] : 0;

        if($this->request->isPost())
        {
            $post = $this->PostModel->find($postid);

            $user = UserModel::find($userid);

            if(!$post)
            {
                $this->error('帖子不存在,请重新选择');
            }

            if(!$user)
            {
                $this->error('请先登录');
            }

            if($user['id'] != $post['userid'])
            {
                $this->error('您没有权限修改他人帖子');
            }

            $params = $this->request->param();

            if(!captcha_check($params['vercode']))
            {
                $this->error('验证码错误，请重新输入');
            }

            $data = [
                'cateid' => $params['cateid'],
                'title' => $params['title'],
                'content' => $params['content']
            ];

            try {
                validate(PostValiDate::class)->scene('edit')->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            $result = $post->save($data);

            if($result !== FALSE)
            {
                $this->success('更新帖子成功',(String)url('/home/post/info',['postid' => $postid]));
            }else{
                $this->error('更新帖子失败');
            }
        }

        $post = $this->PostModel->withJoin(['type'])->find($postid);
        
        if(!$post)
        {
            $this->error('帖子不存在,请重新选择');
        }

        // 查询分类数据
        $CateList = CateModel::order('weigh','desc')->limit(6)->select();

        // 调用Post模型查询状态方法
        $StateList = $this->PostModel->state();

        return view('',[
            'CateList' => $CateList,
            'StateList' => $StateList,
            'post' => $post
        ]);
    }

    // 帖子新增
    public function add()
    {
        $LoginUser = $this->request->LoginUser;

        if($this->request->isPost())
        {
            $vercode = $this->request->param('vercode');

            $user = UserModel::find($LoginUser['id']);

            if(!$user)
            {
                cookie('LoginUser',null);
                $this->error('非法登录',(string)url('/home/index/login'));
            }

            // if(!captcha_check($vercode))
            // {
            //     $this->error('验证码输入错误，请重新输入');
            // }

            $params = $this->request->param();

            // 开启事务操作
            UserModel::startTrans();
            PostModel::startTrans();
            RecordModel::startTrans();

            /* 
                用户表 更新积分 1 save()
                帖子   新增帖子 0
                消费记录 新增消费积分记录
            */

            // 组装用户数据 => 更新用户的积分

            // 首先把悬赏积分+帖子状态积分 让用户积分减它们
            
            // 接收帖子状态再查询config表配置项
            $StatePoint = ConfigModel::where(['key' => "PostState{$params['state']}"])->value('value');

            // 悬赏积分+帖子状态积分
            $Point = bcadd((String)$params['point'],(String)$StatePoint);

            // 用户积分减去 需要的积分 = 扣去后的用户积分
            $point = bcsub((String)$LoginUser['point'],(String)$Point);

            if($point < 0)
            {
                $this->error('积分不足，请及时充值');
            }

            $UserData = [
                'point' => $point
            ];

            $UserStatus = $user->save($UserData);
            

            if($UserStatus === FALSE)
            {
                $this->error('用户积分更新失败');
            }

            // 帖子数据
            $PostData = [
                'title' => $params['title'],
                'content' => $params['content'],
                'point' => $params['point'],
                'state' => $params['state'],
                'userid' => $user['id'],
                'cateid' => $params['cateid']
            ];

            try {
                validate(PostValiDate::class)->check($PostData);
            } catch (ValidateException $e) {
                UserModel::rollback();
                $this->error($e->getMessage());
            }

            $PostStatus = $this->PostModel->save($PostData);

            if($PostStatus === FALSE)
            {
                UserModel::rollback();
                $this->error('帖子发表失败');
            }


            // 消费记录
            $RecordData = [
                'point' => $Point,
                'content' => "您发表的帖子：{$PostData['title']}消费了{$Point}积分",
                'state' => 1,
                'userid' => $user['id']
            ];


            try {
                validate(RecordValiDate::class)->check($RecordData);
            } catch (ValidateException $e) {
                UserModel::rollback();
                PostModel::rollback();
                $this->error($e->getMessage());
            }

            $RecordStatus = $this->RecordModel->save($RecordData);

            if($RecordStatus === FALSE)
            {
                UserModel::rollback();
                PostModel::rollback();
                $this->error('新增消费记录失败');
            }

            if($UserStatus === FALSE || $PostStatus === FALSE || $RecordStatus === FALSE)
            {
                // 回滚
                UserModel::rollback();
                PostModel::rollback();
                RecordModel::rollback();
                $this->error('发表失败');
            }else{
                // 提交事务
                UserModel::commit();
                PostModel::commit();
                RecordModel::commit();
                $this->success('发表成功',(String)url('/home/index/index'));
            }
        }

        // 查询分类数据
        $CateList = CateModel::order('weigh','desc')->limit(6)->select();

        // 调用Post模型查询状态方法
        $StateList = $this->PostModel->state();
        
        return view('',[
            'CateList' => $CateList,
            'StateList' => $StateList
        ]);
    }

    // 帖子删除
    public function del()
    {
        if($this->request->isAjax())
        {
            $postid = $this->request->param('postid');

            $post = $this->PostModel->find($postid);

            if(!$post)
            {
                $this->error('帖子不存在');
            }

            $result = $this->PostModel->destroy($postid);

            if($result !== FALSE)
            {
                $this->success('删除成功',(String)url('/home/index/index'));
            }else{
                $this->error('删除失败');
            }

        }
    }
}
